package com.leyou.order.task;


import com.leyou.order.clients.AuthClient;
import com.leyou.order.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class PrivilegeTokenHolder {

    private String token;

    @Autowired
    private JwtProperties props;

    @Autowired
    private AuthClient authClient;

    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;

    private static final long TOKEN_RETRY_INTERVAL = 10000L;

    @Scheduled(fixedDelay = TOKEN_REFRESH_INTERVAL)
    public void loadToken() throws InterruptedException{
        while(true){
            try {
                this.token = authClient.authorize(props.getApp().getId(),props.getApp().getSecret());
                log.info("【订单服务】定时获取token成功");
                break;
            } catch (Exception e) {
                log.info("【订单服务】定时获取token失败");
            }
            Thread.sleep(TOKEN_RETRY_INTERVAL);
        }
    }

    public String getToken(){
        return token;
    }
}
